package model;

public class StaticInstances 
{

	public static DB _db;
	private static StaticInstances instance;
	public static StaticInstances getInstance()
	{
		if(instance == null)
		{
			instance = new StaticInstances();
		}
		
		return instance;
	}

	private StaticInstances()
	{
		initDB();
	}
	
	private void initDB()
	{
		if(_db == null)
		{
			_db = new DB();
		}
	}
	
	public static String formatDecimal(double decimal, int digits)
	{
		StringBuffer sb = new StringBuffer();
		
		String decimalStr = decimal+"";
		int indexOfDot = decimalStr.indexOf(".");
		
		if(indexOfDot > 0)
		{
			sb.append(decimalStr.substring(0,  indexOfDot));
			String charsAfterDot = decimalStr.substring(indexOfDot+1);
			
			if(charsAfterDot.length() <= digits)
				sb.append(charsAfterDot);
			else
			{
				for(int i=0; i < digits ; i++)
				{
					if(i == digits-1)
					{
						int x = charsAfterDot.charAt(i);
						int y = charsAfterDot.charAt(i+1);
						
						if(y > 5)
						{
							x += 1;
							
							if(x > 9)
							{
								x = 9;
								sb.append(x);
								int lengthSB = sb.length();
								int j = lengthSB - 2;
								boolean finished = false;
								while(!finished && sb.charAt(j) != '.')
								{
									x = Integer.parseInt(sb.charAt(j)+"");
									x = x+ 1 > 9? x : x+1;
									if(x < 10)
									{
										sb.setCharAt(j, (char) x);
										finished = true;
										break;
									}
									else
										j--;
								}
								
								if(!finished)
								{
									int digitsBeforeDot = Integer.parseInt(decimalStr.substring(0,  indexOfDot-1));
									digitsBeforeDot += 1;
									
									char[] digitsAfter = new char[digits];
									sb.getChars(decimalStr.substring(0,  indexOfDot).length(), sb.length(), digitsAfter, 0);
									
									int newDigitsAfterDot =  Integer.parseInt(new String(digitsAfter));
									
									sb = new StringBuffer();
									sb.append(digitsBeforeDot+"."+newDigitsAfterDot);
								}
							}
						}
						
					}else
					{
						sb.append(charsAfterDot.charAt(i));			
					}
				}
			}
		}
		
		return sb.toString();
	}
}
